package com.aijk.commons.mq.utils;

import com.aijk.conifg.PublicConfig;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.lifesea.rocketmq.utils.manager.DefaultMessageProducerManager;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;

/**
 * MQ消息工具类
 */
public class MqUtils {

    private static HashMap<String, DefaultMessageProducerManager> map = new HashMap();

    private MqUtils() {

    }

    /**
     * 提交MQ消息
     *
     * @param group  MQ分组
     * @param topic  消息队列名称
     * @param tag    消息标签
     * @param key    消息ID，唯一性，如果空则默认采用时间戳
     * @param object 消息对象
     * @return
     */
    public static SendResult sendMessage(String group, String topic, String tag, String key, Object object) {
        DefaultMessageProducerManager producerManager;
        if (!map.containsKey(group)) {
            init(group);
        }
        producerManager = map.get(group);
        String keyf;
        if (StringUtils.isBlank(key)) {
            keyf = String.valueOf(System.currentTimeMillis());
        } else {
            keyf = key;
        }
        return producerManager.sendMessage(topic, tag, keyf, object);
    }

    private static synchronized void init(String group) {
        DefaultMessageProducerManager producerManager = new DefaultMessageProducerManager(group, PublicConfig.ROCKETMQ_NAMESRVADDR);
        map.putIfAbsent(group, producerManager);
    }

}
